<?php
/**
 * 在线编辑器控制器
 * @author Halu
 * @createtime 2015-08-25
 */
namespace Admin\Controller;
use Think\Controller;
class EditorController extends InitController {
	

	// 创建编辑器
	public function buildEditor($element='',$edit_conf='') {
		
		if (empty($element)) {
			$element = 'content';
		}
		
		if(empty($edit_conf)){
			$edit_conf = "
				'source', '|', 'undo', 'redo', '|', 'preview', 'print', 'template', 'code', 'cut', 'copy', 'paste',
				'plainpaste', 'wordpaste', '|', 'justifyleft', 'justifycenter', 'justifyright',
				'justifyfull', 'insertorderedlist', 'insertunorderedlist', 'indent', 'outdent', 'subscript',
				'superscript', 'clearhtml', 'quickformat', 'selectall', '|', 'fullscreen', '/',
				'formatblock', 'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold',
				'italic', 'underline', 'strikethrough', 'lineheight', 'removeformat', '|', 'image', 'multiimage',
				'table', 'hr', 'emoticons', 'baidumap', 'pagebreak',
				'anchor', 'link', 'unlink'
			";
		}
		
		$type = strtolower(C('editor'));
		if ($type == 'kindeditor') {
			$upload_json = U('Admin/Editor/upload_json');
			$file_manager_json = U('Admin/Editor/file_manager_json');
			echo <<<EOT
			<link rel="stylesheet" href="/Public/js/kindeditor/themes/default/default.css" />
			<link rel="stylesheet" href="/Public/js/kindeditor/plugins/code/prettify.css" />
			<script charset="utf-8" src="/Public/js/kindeditor/kindeditor-all-min.js"></script>
			<script charset="utf-8" src="/Public/js/kindeditor/lang/zh_CN.js"></script>
			<script charset="utf-8" src="/Public/js/kindeditor/plugins/code/prettify.js"></script>
			<script>
				KindEditor.ready(function(K) {
				window.editor1 = K.create('textarea[name="{$element}"]', {
					items : [
						{$edit_conf}
					],
					cssPath : '/Public/js/kindeditor/plugins/code/prettify.css',
					uploadJson : '{$upload_json}',
					fileManagerJson : '{$file_manager_json}',
					cssData : 'body{font-size:15px;}',
					autoHeightMode : true,
					allowFileManager : true,
					afterBlur: function(){
						this.sync();
					},
					afterCreate : function() {
						var self = this;
						K.ctrl(document, 13, function() {
							self.sync();
							K('form[name=myform]')[0].submit();
						});
						K.ctrl(self.edit.doc, 13, function() {
							self.sync();
							K('form[name=myform]')[0].submit();
						});
					},
					afterChange:function(){
						//判断sub_word函数，如果存在就执行，不存在则return false，不影响其他模块正常使用
						try {
					        if (typeof(eval(layout_sub_word)) == "function") {
					            layout_sub_word();
					        }
					    } catch(e) {}
					    return false;
					},
				});

				
				prettyPrint();

				});
			</script>
EOT;
			
		} elseif ($type == 'ueditor'){
			$ueditor_upload = U('Admin/Editor/ueditor_action');
			$website_url = C('WEBSITE_URL');
			echo <<<EOT
			<script type="text/javascript">
				var website_url = '{$website_url}';
				var ueditor_upload = '{$ueditor_upload}';
			</script>
		    <script type="text/javascript" src="/Public/js/ueditor/ueditor.config.js"></script>
		    <script type="text/javascript" src="/Public/js/ueditor/ueditor.all.js"></script>
		    <script type="text/javascript">
		        var ue = UE.getEditor('{$element}', {
					serverUrl : '{$ueditor_upload}',
				});
		    </script>
EOT;
		}
	}
	
	// kindedior上传
	public function upload_json() {
		$dir_name = empty($_GET['dir']) ? '' : trim($_GET['dir']);
		if (!in_array($dir_name, array('', 'image', 'flash', 'media', 'file'))) {
			echo "Invalid action name.";
			exit;
		}
		$info = $this->upload($dir_name);
		if ($info) {
			echo json_encode(array('error' => 0, 'url' => '/' . $info['savepath'] . $info['savename']));
		} else {
			echo json_encode(array('error' => 1, 'message' => '文件上传失败，可能网络问题，请稍后再试。'));
		}
		exit;
	}
	
	// kindeditor图片空间管理
	public function file_manager_json() {
		$uploadPath = C('upload_path') . '/';

		//根目录路径，可以指定绝对路径，比如 /var/www/attached/
		$root_path = WEB_ROOT . $uploadPath;
		//根目录URL，可以指定绝对路径，比如 http://www.yoursite.com/attached/
		$root_url = '/' . $uploadPath;
		//图片扩展名
		$ext_arr = array('gif', 'jpg', 'jpeg', 'png', 'bmp');
		
		//目录名
		$dir_name = empty($_GET['dir']) ? '' : trim($_GET['dir']);
		if (!in_array($dir_name, array('', 'image', 'flash', 'media', 'file'))) {
			echo "Invalid Directory name.";
			exit;
		}
		if ($dir_name !== '') {
			$root_path .= $dir_name . "/";
			$root_url .= $dir_name . "/";
			if (!file_exists($root_path)) {
				mkdir($root_path);
			}
		}
		
		//根据path参数，设置各路径和URL
		if (empty($_GET['path'])) {
			$current_path = realpath($root_path) . '/';
			$current_url = $root_url;
			$current_dir_path = '';
			$moveup_dir_path = '';
		} else {
			$current_path = realpath($root_path) . '/' . $_GET['path'];
			$current_url = $root_url . $_GET['path'];
			$current_dir_path = $_GET['path'];
			$moveup_dir_path = preg_replace('/(.*?)[^\/]+\/$/', '$1', $current_dir_path);
		}

		//排序形式，name or size or type
		$GLOBALS['kindeditor_order'] = empty($_GET['order']) ? 'name' : strtolower($_GET['order']);
		
		//不允许使用..移动到上一级目录
		if (preg_match('/\.\./', $current_path)) {
			echo 'Access is not allowed.';
			exit;
		}
		//最后一个字符不是/
		if (!preg_match('/\/$/', $current_path)) {
			echo 'Parameter is not valid.';
			exit;
		}
		//目录不存在或不是目录
		if (!file_exists($current_path) || !is_dir($current_path)) {
			echo 'Directory does not exist.';
			exit;
		}
		
		//遍历目录取得文件信息
		$file_list = array();
		if ($handle = opendir($current_path)) {
			$i = 0;
			while (false !== ($filename = readdir($handle))) {
				if ($filename{0} == '.') continue;
				$file = $current_path . $filename;
				if (is_dir($file)) {
					$file_list[$i]['is_dir'] = true; //是否文件夹
					$file_list[$i]['has_file'] = (count(scandir($file)) > 2); //文件夹是否包含文件
					$file_list[$i]['filesize'] = 0; //文件大小
					$file_list[$i]['is_photo'] = false; //是否图片
					$file_list[$i]['filetype'] = ''; //文件类别，用扩展名判断
				} else {
					$file_list[$i]['is_dir'] = false;
					$file_list[$i]['has_file'] = false;
					$file_list[$i]['filesize'] = filesize($file);
					$file_list[$i]['dir_path'] = '';
					$file_ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
					$file_list[$i]['is_photo'] = in_array($file_ext, $ext_arr);
					$file_list[$i]['filetype'] = $file_ext;
				}
				$file_list[$i]['filename'] = $filename; //文件名，包含扩展名
				$file_list[$i]['datetime'] = date('Y-m-d H:i:s', filemtime($file)); //文件最后修改时间
				$i++;
			}
			closedir($handle);
		}
		
		usort($file_list, 'kineditor_cmp_func');
		
		$result = array();
		//相对于根目录的上一级目录
		$result['moveup_dir_path'] = $moveup_dir_path;
		//相对于根目录的当前目录
		$result['current_dir_path'] = $current_dir_path;
		//当前目录的URL
		$result['current_url'] = $current_url;
		//文件数
		$result['total_count'] = count($file_list);
		//文件列表数组
		$result['file_list'] = $file_list;
		
		//输出JSON字符串
		echo json_encode($result);
	}
	
	// ueditor操作
	public function ueditor_action() {
		$CONFIG = json_decode(preg_replace("/\/\*[\s\S]+?\*\//", "", file_get_contents("Public/js/ueditor/config.json")), true);
		$action = $_GET['action'];
		
		switch ($action) {
			case 'config':
				$result =  json_encode($CONFIG);
				break;
				/* 上传图片 */
			case 'uploadimage':
				/* 上传涂鸦 */
			case 'uploadscrawl':
				/* 上传视频 */
			case 'uploadvideo':
				/* 上传文件 */
			case 'uploadfile':
				$info = $this->upload('image');
				if ($info) {
					$result = array('state'=>'SUCCESS','url'=>'/' . $info['savepath'] . $info['savename'],'title'=>$info['savename'],'original'=>$info['name'],'type'=>$info['type'],'size'=>'.' . $info['ext']);
					$result = json_encode($result);
				} else {
					$result = array('state'=>'SUCCESS','url'=>'','title'=>'','original'=>'','type'=>'');
					$result = json_encode($result);
				}
				break;
				/* 列出图片 */
			case 'listimage':
				$allowFiles = $CONFIG['imageManagerAllowFiles'];
				$listSize = $CONFIG['imageManagerListSize'];
				$path = $CONFIG['imageManagerListPath'];
				break;
				/* 列出文件 */
			case 'listfile':
				$allowFiles = $CONFIG['fileManagerAllowFiles'];
        		$listSize = $CONFIG['fileManagerListSize'];
        		$path = $CONFIG['fileManagerListPath'];
				break;
			/* 抓取远程文件 */
			case 'catchimage':
				// TODO
				/* 上传配置 */
				$config = array(
					"pathFormat" => $CONFIG['catcherPathFormat'],
					"maxSize" => $CONFIG['catcherMaxSize'],
					"allowFiles" => $CONFIG['catcherAllowFiles'],
					"oriName" => "remote.png"
				);
				$fieldName = $CONFIG['catcherFieldName'];
				
				/* 抓取远程图片 */
				$list = array();
				if (isset($_POST[$fieldName])) {
					$source = $_POST[$fieldName];
				} else {
					$source = $_GET[$fieldName];
				}
				
				if (empty($source)) {
					$result = json_encode(array('state'=> 'ERROR','list'=> ''));
					echo $result;exit;
				}
				
				$upload = new \Think\Upload();
				$upload->maxSize  = C('upload_max_size') ;
				$upload->exts     = C('upload_allow_exts');
				$upload->rootPath = C('upload_path') . '/image/';
				$upload->autoSub  = C('upload_autosub');
				$upload->subName  = C('upload_subname');
				
				$attaModel = M('Attachment');
				// 上传文件
				foreach ($source as $imgUrl) {
					$info = $upload->saveRemote($imgUrl, $fieldName);
					if (!$info) {
					//	echo $upload->getError();exit();
						continue;
					}
					$info[$fieldName]['savepath'] = $upload->rootPath . $info[$fieldName]['savepath'];
					// 查询数据库图片是否存在
					$attaInfo = $attaModel->where(array('authcode'=>$info[$fieldName]['md5']))->find();
					if ($attaInfo) {
						// 删除上传的文件
						$filename = $info[$fieldName]['savepath'] . $info[$fieldName]['savename'];
						@unlink($filename);
						$info[$fieldName]['savepath'] = $attaInfo['filepath'];
						$info[$fieldName]['savename'] = $attaInfo['filename'];
						$info[$fieldName]['size'] = $attaInfo['filesize'];
						$info[$fieldName]['ext'] = $attaInfo['fileext'];
					} else {
						//记录数据库
						$_filetype = $info[$fieldName]['type'];
						$data['filename'] = $info[$fieldName]['savename'];
						$data['filepath'] = $info[$fieldName]['savepath'];
						$data['filetype'] = $info[$fieldName]['type'];
						$data['filesize'] = $info[$fieldName]['size'];
						$data['fileext']  = $info[$fieldName]['ext'];
						$data['isimage']  = 1;
						$data['isthumb']  = 0;
						$data['userid']   = session('uid');
						$data['uploadtime'] = NOW_TIME;
						$data['status'] = 1;
						$data['authcode'] =  $info[$fieldName]['md5'];
						$attaModel->add($data);
					}
					
					array_push($list, array(
						"state" => 'SUCCESS',
						"url" => '/' . $info['savepath'] . $info['savename'],
						"size" => '.' . $info["size"],
						"title" => htmlspecialchars($info["savename"]),
						"original" => htmlspecialchars($info["name"]),
						"source" => htmlspecialchars($imgUrl)
					));
				}
				die;
				/* 返回抓取数据 */
				$result = json_encode(array(
					'state'=> count($list) ? 'SUCCESS':'ERROR',
					'list'=> $list
				));
				
				break;
			default:
				$result = json_encode(array(
				'state'=> '请求地址出错'
						));
				break;
		}
		
		//列出图片/列出文件
		if ($action == 'listimage' || $action == 'listfile') {
			$allowFiles = substr(str_replace(".", "|", join("", $allowFiles)), 1);

			/* 获取参数 */
			$size = isset($_GET['size']) ? htmlspecialchars($_GET['size']) : $listSize;
			$start = isset($_GET['start']) ? htmlspecialchars($_GET['start']) : 0;
			$end = $start + $size;
			
			/* 获取文件列表 */
			$path = $_SERVER['DOCUMENT_ROOT'] . (substr($path, 0, 1) == "/" ? "":"/") . $path;
			$files = ueditor_getfiles($path, $allowFiles);
			
			if (!count($files)) {
				return json_encode(array(
					"state" => "no match file",
					"list" => array(),
					"start" => $start,
					"total" => count($files)
				));
			}
			
			/* 获取指定范围的列表 */
			$len = count($files);
			for ($i = min($end, $len) - 1, $list = array(); $i < $len && $i >= 0 && $i >= $start; $i--){
				$list[] = $files[$i];
			}
			//倒序
			//for ($i = $end, $list = array(); $i < $len && $i < $end; $i++){
			//    $list[] = $files[$i];
			//}
			
			/* 返回数据 */
			$result = json_encode(array(
				"state" => "SUCCESS",
				"list" => $list,
				"start" => $start,
				"total" => count($files)
			));
		}
		
		/* 输出结果 */
		if (isset($_GET["callback"])) {
			if (preg_match("/^[\w_]+$/", $_GET["callback"])) {
				echo htmlspecialchars($_GET["callback"]) . '(' . $result . ')';
			} else {
				echo json_encode(array('state'=> 'callback参数不合法'));
			}
		} else {
			echo $result;
		}
	}
	
}